package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// DeviceGroup 设备分组模型
type DeviceGroup struct {
	BaseModel
	Name        string `orm:"size(100)" json:"name"`        // 分组名称
	Description string `orm:"size(500)" json:"description"` // 分组描述
	DeviceCount int    `orm:"-" json:"device_count"`        // 设备数量（非数据库字段）
}

// DeviceGroupRelation 设备与分组关联模型
type DeviceGroupRelation struct {
	BaseModel
	DeviceId int64 `orm:"index" json:"device_id"` // 设备ID
	GroupId  int64 `orm:"index" json:"group_id"`  // 分组ID
}

// TableName 设置表名
func (g *DeviceGroup) TableName() string {
	return "ss_device_group"
}

// TableName 设置表名
func (r *DeviceGroupRelation) TableName() string {
	return "ss_device_group_relation"
}

// GetDeviceGroupList 获取设备分组列表
func GetDeviceGroupList(page, pageSize int, filters map[string]interface{}) ([]*DeviceGroup, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(DeviceGroup))

	// 应用过滤条件
	if keyword, ok := filters["keyword"].(string); ok && keyword != "" {
		qs = qs.Filter("name__icontains", keyword)
	}

	// 加盟商权限过滤
	if franchiseId, ok := filters["franchise_id"].(int64); ok && franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 多个加盟商ID过滤
	if franchiseIds, ok := filters["franchise_ids"].([]int64); ok && len(franchiseIds) > 0 {
		qs = qs.Filter("franchise_id__in", franchiseIds)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var groups []*DeviceGroup
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&groups)

	if err != nil {
		return nil, 0, err
	}

	// 填充每个分组的设备数量
	for _, group := range groups {
		// 获取分组下的设备计数（只统计未删除的设备）
		var relations []*DeviceGroupRelation
		_, err := o.QueryTable(new(DeviceGroupRelation)).Filter("group_id", group.Id).All(&relations)
		if err != nil {
			continue // 如果查询失败，则跳过此分组
		}

		if len(relations) == 0 {
			group.DeviceCount = 0
			continue
		}

		deviceIds := make([]int64, len(relations))
		for i, r := range relations {
			deviceIds[i] = r.DeviceId
		}

		count, err := o.QueryTable(new(Device)).Filter("id__in", deviceIds).Filter("is_deleted", 0).Count()
		if err != nil {
			group.DeviceCount = 0 // 查询失败时设为0
		} else {
			group.DeviceCount = int(count)
		}
	}

	return groups, total, err
}

// GetDeviceGroupById 根据ID获取设备分组
func GetDeviceGroupById(id int64) (*DeviceGroup, error) {
	o := orm.NewOrm()
	group := &DeviceGroup{BaseModel: BaseModel{Id: id}}
	err := o.Read(group)
	if err != nil {
		return nil, err
	}

	// 获取分组下的设备计数（只统计未删除的设备）
	var relations []*DeviceGroupRelation
	_, err = o.QueryTable(new(DeviceGroupRelation)).Filter("group_id", id).All(&relations)
	if err != nil {
		return group, nil // 返回组信息但不包含计数
	}

	// 如果没有设备关系记录，设备计数为0
	if len(relations) == 0 {
		group.DeviceCount = 0
		return group, nil
	}

	// 提取设备ID
	deviceIds := make([]int64, len(relations))
	for i, relation := range relations {
		deviceIds[i] = relation.DeviceId
	}

	// 查询有效设备数量
	count, err := o.QueryTable(new(Device)).Filter("id__in", deviceIds).Filter("is_deleted", 0).Count()
	if err != nil {
		group.DeviceCount = 0 // 出错时设为0
	} else {
		group.DeviceCount = int(count)
	}

	return group, nil
}

// GetDeviceGroupByIdWithFranchise 根据ID获取设备分组（支持加盟商权限验证）
func GetDeviceGroupByIdWithFranchise(id int64, franchiseId int64) (*DeviceGroup, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(DeviceGroup)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商权限过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	group := &DeviceGroup{}
	err := qs.One(group)
	if err != nil {
		return nil, err
	}

	// 获取分组下的设备计数
	var relations []*DeviceGroupRelation
	_, err = o.QueryTable(new(DeviceGroupRelation)).Filter("group_id", id).All(&relations)
	if err == nil {
		if len(relations) == 0 {
			group.DeviceCount = 0
		} else {
			// 提取设备ID
			deviceIds := make([]int64, len(relations))
			for i, relation := range relations {
				deviceIds[i] = relation.DeviceId
			}
			// 查询有效设备数量
			count, err := o.QueryTable(new(Device)).Filter("id__in", deviceIds).Filter("is_deleted", 0).Count()
			if err == nil {
				group.DeviceCount = int(count)
			} else {
				group.DeviceCount = 0
			}
		}
	}

	return group, nil
}

// CreateDeviceGroup 创建设备分组
func CreateDeviceGroup(group *DeviceGroup) (int64, error) {
	o := orm.NewOrm()
	group.CreatedAt = time.Now().Unix()
	group.UpdatedAt = group.CreatedAt
	id, err := o.Insert(group)
	return id, err
}

// UpdateDeviceGroup 更新设备分组
func UpdateDeviceGroup(group *DeviceGroup) error {
	o := orm.NewOrm()
	group.UpdatedAt = time.Now().Unix()
	_, err := o.Update(group, "Name", "Description", "UpdatedAt")
	return err
}

// UpdateDeviceGroupWithFranchise 更新设备分组（支持加盟商权限验证）
func UpdateDeviceGroupWithFranchise(group *DeviceGroup, franchiseId int64) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(DeviceGroup)).Filter("id", group.Id).Filter("is_deleted", 0)

	// 加盟商权限过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	existingGroup := &DeviceGroup{}
	err := qs.One(existingGroup)
	if err != nil {
		return err
	}

	// 保持原有的加盟商ID
	group.FranchiseId = existingGroup.FranchiseId
	group.UpdatedAt = time.Now().Unix()

	_, err = o.Update(group, "Name", "Description", "UpdatedAt")
	return err
}

// DeleteDeviceGroup 删除设备分组（软删除）
func DeleteDeviceGroup(id int64) error {
	o := orm.NewOrm()
	group := &DeviceGroup{BaseModel: BaseModel{Id: id}}
	if err := o.Read(group); err != nil {
		return err
	}

	group.IsDeleted = 1
	group.UpdatedAt = time.Now().Unix()
	_, err := o.Update(group, "IsDeleted", "UpdatedAt")

	// 删除分组关联关系
	if err == nil {
		_, err = o.QueryTable(new(DeviceGroupRelation)).Filter("group_id", id).Delete()
	}

	return err
}

// DeleteDeviceGroupWithFranchise 删除设备分组（软删除，支持加盟商权限验证）
func DeleteDeviceGroupWithFranchise(id int64, franchiseId int64) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(DeviceGroup)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商权限过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	group := &DeviceGroup{}
	err := qs.One(group)
	if err != nil {
		return err
	}

	group.IsDeleted = 1
	group.UpdatedAt = time.Now().Unix()

	_, err = o.Update(group, "IsDeleted", "UpdatedAt")

	// 删除分组关联关系
	if err == nil {
		_, err = o.QueryTable(new(DeviceGroupRelation)).Filter("group_id", id).Delete()
	}

	return err
}

// BatchAddDevicesToGroup 批量添加设备到分组
func BatchAddDevicesToGroup(deviceIds []int64, groupId int64) error {
	o := orm.NewOrm()

	// 开启事务
	tx, err := o.Begin()
	if err != nil {
		return err
	}

	// 先删除已存在的关联
	_, err = o.QueryTable(new(DeviceGroupRelation)).Filter("group_id", groupId).Filter("device_id__in", deviceIds).Delete()
	if err != nil {
		tx.Rollback()
		return err
	}

	// 批量插入新关联
	for _, deviceId := range deviceIds {
		relation := &DeviceGroupRelation{
			DeviceId: deviceId,
			GroupId:  groupId,
		}
		relation.BeforeInsert()
		_, err = o.Insert(relation)
		if err != nil {
			tx.Rollback()
			return err
		}
	}

	// 提交事务
	return tx.Commit()
}

// BatchRemoveDevicesFromGroup 批量从分组中移除设备
func BatchRemoveDevicesFromGroup(deviceIds []int64, groupId int64) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(DeviceGroupRelation)).Filter("group_id", groupId).Filter("device_id__in", deviceIds).Delete()
	return err
}

// GetDevicesByGroupId 获取分组下的设备列表
func GetDevicesByGroupId(groupId int64, page, pageSize int) ([]*Device, int64, error) {
	o := orm.NewOrm()

	// 获取分组下的设备ID列表
	var relations []*DeviceGroupRelation
	_, err := o.QueryTable(new(DeviceGroupRelation)).Filter("group_id", groupId).All(&relations)
	if err != nil {
		return nil, 0, err
	}

	// 如果没有设备，直接返回空列表
	if len(relations) == 0 {
		return []*Device{}, 0, nil
	}

	// 提取设备ID
	deviceIds := make([]int64, len(relations))
	for i, relation := range relations {
		deviceIds[i] = relation.DeviceId
	}

	// 查询设备信息，只统计未删除的设备
	qs := o.QueryTable(new(Device)).Filter("id__in", deviceIds).Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var devices []*Device
	_, err = qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&devices)

	return devices, total, err
}

// GetGroupsByDeviceId 获取设备所属的分组列表
func GetGroupsByDeviceId(deviceId int64) ([]*DeviceGroup, error) {
	o := orm.NewOrm()

	// 获取设备所属的分组ID列表
	var relations []*DeviceGroupRelation
	_, err := o.QueryTable(new(DeviceGroupRelation)).Filter("device_id", deviceId).All(&relations)
	if err != nil {
		return nil, err
	}

	// 如果没有分组，直接返回空列表
	if len(relations) == 0 {
		return []*DeviceGroup{}, nil
	}

	// 提取分组ID
	groupIds := make([]int64, len(relations))
	for i, relation := range relations {
		groupIds[i] = relation.GroupId
	}

	// 查询分组信息
	var groups []*DeviceGroup
	_, err = o.QueryTable(new(DeviceGroup)).Filter("id__in", groupIds).Filter("is_deleted", 0).All(&groups)

	return groups, err
}

// AddDevicesToGroup 添加设备到分组
func AddDevicesToGroup(groupId int64, deviceIds []int64) error {
	o := orm.NewOrm()
	for _, deviceId := range deviceIds {
		_, err := o.Raw("INSERT INTO ss_device_group_rel (group_id, device_id) VALUES (?, ?)", groupId, deviceId).Exec()
		if err != nil {
			return err
		}
	}
	return nil
}

// RemoveDevicesFromGroup 从分组中移除设备
func RemoveDevicesFromGroup(groupId int64, deviceIds []int64) error {
	o := orm.NewOrm()
	for _, deviceId := range deviceIds {
		_, err := o.Raw("DELETE FROM ss_device_group_rel WHERE group_id = ? AND device_id = ?", groupId, deviceId).Exec()
		if err != nil {
			return err
		}
	}
	return nil
}
